package mqtt;

import org.eclipse.paho.client.mqttv3.*;

// 重连的回调函数
public abstract class ReconnectMqttCallback implements MqttCallback {

    private MqttConnectOptions options;
    private MqttClient client;
    private String topic;
    private int qos;

    public ReconnectMqttCallback(MqttConnectOptions options, MqttClient client, String topic, int qos) {
        this.options = options;
        this.client = client;
        this.topic = topic;
        this.qos = qos;
    }

    // 连接断开调用 reconnect 方法重连
    @Override
    public void connectionLost(Throwable throwable) {
        System.out.println("Connection lost, reconnecting...");
        reconnect();
    }

    // 先判断是否连接，没有连接就先等待十秒重新连接，一直循环到连接上为止
    public void reconnect() {
        while (!client.isConnected()) {
            try {
                Thread.sleep(1000 * 10);// 10s 重连一次
                client.connect(options);
                client.subscribe(topic,qos);
            } catch (MqttException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
